<template>
  <div class="travel-chat">
    <div class="chat-header">
      <h3>智能旅行助手</h3>
      <button class="save-chat-btn" @click="openSaveDialog">
        <i class="fas fa-save"></i> 保存行程
      </button>
    </div>
    <div class="chat-messages" ref="messageContainer">
      <div v-for="(message, index) in messages" :key="index" class="message" :class="message.isUser ? 'user-message' : 'ai-message'">
        <div class="message-content">{{ message.content }}</div>
      </div>
      <div v-if="isLoading" class="message ai-message">
        <div class="message-content loading">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input 
        type="text" 
        v-model="userInput" 
        placeholder="输入您想了解的旅行信息..." 
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage" :disabled="isLoading || !userInput.trim()">发送</button>
    </div>
    
    <!-- 保存对话框 -->
    <div class="modal-overlay" v-if="showSaveDialog" @click="closeSaveDialog">
      <div class="save-dialog" @click.stop>
        <h3>保存您的旅行计划</h3>
        <div class="form-group">
          <label for="trip-title">旅行主题</label>
          <input 
            type="text" 
            id="trip-title" 
            v-model="tripData.title" 
            placeholder="例如：北京五日游"
          />
        </div>
        <div class="form-group">
          <label for="trip-requirements">旅行需求</label>
          <textarea 
            id="trip-requirements" 
            v-model="tripData.requirements" 
            placeholder="描述您的具体需求，如预算、喜好等..."
            rows="3"
          ></textarea>
        </div>
        <div class="date-row">
          <div class="form-group">
            <label for="start-date">开始日期</label>
            <input 
              type="date" 
              id="start-date" 
              v-model="tripData.startDate"
            />
          </div>
          <div class="form-group">
            <label for="end-date">结束日期</label>
            <input 
              type="date" 
              id="end-date" 
              v-model="tripData.endDate"
            />
          </div>
        </div>
        <div class="dialog-buttons">
          <button class="cancel-btn" @click="closeSaveDialog">取消</button>
          <button class="save-btn" @click="saveTripData" :disabled="!isTripDataValid">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import { sendChatMessage, processStreamResponse } from '@/api/chat';

// 聊天消息数组
const messages = ref([
  {
    content: "您好！我是您的旅行助手。请告诉我您想去哪里旅行，我可以为您提供路线规划和建议。",
    isUser: false
  }
]);

// 用户输入
const userInput = ref('');
// 加载状态
const isLoading = ref(false);
// 消息容器，用于自动滚动
const messageContainer = ref(null);
// 当前会话ID
const sessionId = ref('');
// 流式处理的临时消息存储
const currentStreamMessage = ref('');

// 保存对话框状态
const showSaveDialog = ref(false);
// 旅行数据
const tripData = reactive({
  title: '',
  requirements: '',
  startDate: '',
  endDate: '',
  chatHistory: []
});

// 验证旅行数据是否有效
const isTripDataValid = computed(() => {
  return tripData.title.trim() !== '' && 
         tripData.startDate !== '' && 
         tripData.endDate !== '';
});

// 打开保存对话框
const openSaveDialog = () => {
  // 将当前聊天记录复制到tripData
  tripData.chatHistory = [...messages.value];
  
  // 设置默认日期（如果未设置）
  if (!tripData.startDate) {
    const today = new Date();
    tripData.startDate = today.toISOString().split('T')[0];
    
    // 默认结束日期为7天后
    const endDate = new Date();
    endDate.setDate(today.getDate() + 7);
    tripData.endDate = endDate.toISOString().split('T')[0];
  }
  
  showSaveDialog.value = true;
};

// 关闭保存对话框
const closeSaveDialog = () => {
  showSaveDialog.value = false;
};

// 保存旅行数据
const saveTripData = () => {
  // 实际应该发送到后端保存
  console.log('保存旅行数据:', tripData);
  
  // 创建一个成功消息
  const successMessage = {
    content: `您的旅行计划「${tripData.title}」已保存成功！旅行日期：${tripData.startDate} 至 ${tripData.endDate}`,
    isUser: false
  };
  
  // 添加到聊天记录
  messages.value.push(successMessage);
  
  // 关闭对话框
  closeSaveDialog();
  
  // 滚动到底部以显示成功消息
  scrollToBottom();
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;
  
  // 添加用户消息
  const userMessage = userInput.value;
  messages.value.push({
    content: userMessage,
    isUser: true
  });
  
  // 清空输入框
  userInput.value = '';
  // 设置加载状态
  isLoading.value = true;
  
  try {
    // 调用API发送消息，获取流式响应
    // 首次请求不传sessionId，使用服务器生成的sessionId
    const stream = await sendChatMessage(userMessage, sessionId.value);
    
    // 初始化当前消息
    currentStreamMessage.value = '';
    
    // 创建一个空的AI回复消息
    messages.value.push({
      content: '',
      isUser: false
    });
    
    // 处理流式响应
    await processStreamResponse(
      stream,
      // 每次收到数据块的处理
      (data) => {
        // 更新当前流消息
        if (data.message !== undefined) {
          currentStreamMessage.value += data.message;
          // 更新最后一条AI消息的内容
          const lastMessageIndex = messages.value.length - 1;
          messages.value[lastMessageIndex].content = currentStreamMessage.value;
        }
        
        // 如果是最后一个块，更新sessionId
        if (data.sessionId) {
          sessionId.value = data.sessionId;
        }
      },
      // 错误处理
      (error) => {
        console.error('处理响应出错:', error);
      },
      // 完成处理
      () => {
        isLoading.value = false;
        scrollToBottom();
      }
    );
  } catch (error) {
    console.error('发送消息出错:', error);
    messages.value.push({
      content: "抱歉，我遇到了一些问题。请稍后再试。",
      isUser: false
    });
    isLoading.value = false;
    scrollToBottom();
  }
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

// 监听消息变化，自动滚动
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// 组件挂载后初始化
onMounted(() => {
  // 如果需要在挂载时做一些初始化，可以在这里添加
  scrollToBottom();
});
</script>

<style scoped>
.travel-chat {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  position: relative; /* 位置相对定位 */
  max-height: 700px; /* 设置最大高度 */
}

.chat-header {
  padding: 15px 20px;
  background-color: #16a34a;
  color: white;
  flex-shrink: 0; /* 防止头部被压缩 */
  position: sticky; /* 固定在顶部 */
  top: 0;
  z-index: 20; /* 确保在最上层 */
  display: flex; /* 使用flex布局使标题和按钮水平对齐 */
  justify-content: space-between; /* 标题靠左，按钮靠右 */
  align-items: center; /* 垂直居中 */
}

.chat-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.save-chat-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background-color 0.2s;
}

.save-chat-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto; /* 启用垂直滚动 */
  display: flex;
  flex-direction: column;
  gap: 16px;
  scrollbar-width: thin; /* Firefox 滚动条样式 */
  scrollbar-color: #d1d5db #f3f4f6; /* Firefox 滚动条颜色 */
  position: relative; /* 为绝对定位的子元素提供参考 */
}

/* Webkit浏览器的滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f3f4f6;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #d1d5db;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background-color: #9ca3af;
}

.message {
  max-width: 85%; /* 增加最大宽度，允许更多文本显示 */
  padding: 12px 16px;
  border-radius: 12px;
  animation: fadeIn 0.3s ease-out;
  word-break: break-word; /* 在单词之间换行 */
  white-space: pre-wrap; /* 保留空格和换行符 */
  overflow-wrap: break-word; /* 确保长单词能够换行 */
  hyphens: auto; /* 启用连字符 */
}

.user-message {
  align-self: flex-end;
  background-color: #dcfce7;
  color: #166534;
}

.ai-message {
  align-self: flex-start;
  background-color: #f3f4f6;
  color: #1f2937;
}

.message-content {
  line-height: 1.5;
  word-break: break-word;
  max-height: 300px; /* 限制单个消息的最大高度 */
  overflow-y: auto; /* 启用垂直滚动 */
  scrollbar-width: thin; /* Firefox 滚动条样式 */
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent; /* Firefox 滚动条颜色 */
  padding-right: 4px; /* 为滚动条预留空间 */
}

/* 单个消息的滚动条样式 */
.message-content::-webkit-scrollbar {
  width: 4px;
}

.message-content::-webkit-scrollbar-track {
  background: transparent;
}

.message-content::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 2px;
}

.message-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.8);
}

.chat-input {
  padding: 15px;
  display: flex;
  gap: 10px;
  border-top: 1px solid #e5e7eb;
  flex-shrink: 0; /* 防止输入框被压缩 */
  background-color: white; /* 确保输入区域有背景色 */
  position: sticky; /* 固定在底部 */
  bottom: 0;
  z-index: 20; /* 确保在最上层 */
}

.chat-input input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.2s;
}

.chat-input input:focus {
  border-color: #16a34a;
}

.chat-input button {
  padding: 10px 24px;
  background-color: #16a34a;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap; /* 防止按钮文字换行 */
}

.chat-input button:hover:not(:disabled) {
  background-color: #15803d;
}

.chat-input button:disabled {
  background-color: #94a3b8;
  cursor: not-allowed;
}

/* 加载动画 */
.loading {
  display: flex;
  gap: 5px;
}

.loading span {
  width: 10px;
  height: 10px;
  background-color: #94a3b8;
  border-radius: 50%;
  display: inline-block;
  animation: loadingBounce 1.4s infinite ease-in-out both;
}

.loading span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading span:nth-child(2) {
  animation-delay: -0.16s;
}

/* 保存对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  animation: fadeIn 0.2s ease-out;
}

.save-dialog {
  background-color: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  padding: 24px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
  animation: dialogSlideIn 0.3s ease-out;
}

.save-dialog h3 {
  font-size: 20px;
  margin: 0 0 20px 0;
  color: #1f2937;
  text-align: center;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
  margin-bottom: 6px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 15px;
  outline: none;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #16a34a;
  box-shadow: 0 0 0 2px rgba(22, 163, 74, 0.1);
}

.date-row {
  display: flex;
  gap: 16px;
}

.date-row .form-group {
  flex: 1;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.cancel-btn {
  padding: 10px 16px;
  background-color: #f3f4f6;
  color: #4b5563;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cancel-btn:hover {
  background-color: #e5e7eb;
}

.save-btn {
  padding: 10px 20px;
  background-color: #16a34a;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.save-btn:hover:not(:disabled) {
  background-color: #15803d;
}

.save-btn:disabled {
  background-color: #94a3b8;
  cursor: not-allowed;
  opacity: 0.7;
}

@keyframes dialogSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes loadingBounce {
  0%, 80%, 100% { 
    transform: scale(0);
  } 
  40% { 
    transform: scale(1.0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 平板和移动设备的响应式设计 */
@media (max-width: 768px) {
  .travel-chat {
    max-height: 500px; /* 移动设备上减小最大高度 */
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-messages {
    padding: 12px;
    gap: 12px;
  }
  
  .chat-input {
    padding: 12px;
  }
  
  .date-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .save-dialog {
    padding: 20px;
    width: 95%;
  }
}
</style> 